<!-- 路径规划组件 -->
<!-- 操作：面板上选择起点和终点，然后点击进入规划模式，进行路径规划 -->
<!-- 路径规划期间，将禁用图层控制，并将图层隐藏，展示路径规划实体以及规划面板 -->
<!-- 点击离开规划，恢复图层控制，并清除规划的结果，隐藏规划面板 -->
<template>
  <div class="route-design-wrapper">
    <div class="route-design">
      <div class="header">
        <i class="iconfont metro-lujingguihua"></i>
        <span>路径规划</span>
        <button class="start-btn" @click="enterDesign">
          {{ isDesign ? '离开规划模式' : '进入规划模式' }}
        </button>
      </div>
      <div class="content">
        <div>
          <span style="margin-right: 5px">起点:</span>
          <a-cascader
            v-model:value="startStation"
            :options="options"
            placeholder="请输入起点站"
          >
            <template #clearIcon>
              <i class="iconfont metro-close"></i>
            </template>
          </a-cascader>
          <!-- <a-button style="margin-left: 8px" @click="pickStation('origin')">拾取起点站</a-button> -->
        </div>
        <div>
          <span style="margin-right: 5px">终点:</span>
          <a-cascader
            v-model:value="endStation"
            :options="options"
            placeholder="请输入起点站"
            ><template #clearIcon>
              <i class="iconfont metro-close"></i>
            </template>
          </a-cascader>
        </div>
      </div>
    </div>
  </div>
  <!-- 路径规划展示面板 -->
  <PathDesignDisplayCard
    :routeInfo="routeInfo"
    v-if="isDesign"
    :cacheData="cacheData"
  />
</template>
<script setup>
import { ref,onMounted,watch,onBeforeUnmount } from 'vue'
import { useLineData } from '@/store'
import { message } from 'ant-design-vue';
import PathDesignDisplayCard from './PathDesignDisplayCard.vue'
import { renderStation,renderStationBill, renderLines,removeByCacheData, flyToDefaultView } from '@/cesiumTools/material/effectController.js'
import { getLinePlan } from '@/api/line.js'


const lineData = useLineData()
const subLineData = ref([])//线路数据
const startStation = ref([])//规划起点站
const endStation = ref([])//规划终点站
const isDesign = ref(false) // 是否进入规划模式
const lineColors = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF', '#FFFFFF']
let viewer = null
// 路径规划数据
const routeInfo = ref({
    distance:[],
    stations:[]
})
// 存放在列表组件中，用来点击跳转
const cacheData = {
    stationEnts:[],
    billboards:[],
    lineEnts:[]
}


// 获取起点/终点站的经纬度坐标
const getPosition = (lineName, stationName) => {
    const target = subLineData.value.find(item => item.name === lineName)
    const {position} = target.stationsList.find(item => item.name === stationName)

    return `${position.lng},${position.lat}`
}
// 获取线路规划数据数据
const getLineData = async ()=>{
    const params = {}
    params.origin = getPosition(startStation.value[0], startStation.value[1])
    params.destination = getPosition(endStation.value[0], endStation.value[1])
    // console.log(params)
    const res = await getLinePlan(params)
    console.log(res)
    if(res.code === 200){
        return res.data
    }else{
        message.warn('查询不到相关数据')
        return null
    }
}
// 渲染线路
const renderLine = (data)=>{
    lineData.controlAll(false)
    removeActiveEnts()
    const { distance, segments } = data;
    //存储路径规划的距离
    routeInfo.value.distance = distance
    const stations = []// 站点数据
    const path = []//路径数据
    console.log(segments)
    segments.forEach((item,index)=>{
        const {bus:{buslines}} = item
        // console.log(buslines)
        // buslines可能是null
        if(buslines?.length){
            // 存储路径规划的站点
            const target = buslines[0]
            target.color = lineColors[index]
            // console.log(target)
            routeInfo.value.stations.push(target)
            // busline是每一段的公交信息
            buslines.forEach(busline=>{
                /*
                    arrival_stop: 每一段的到达站
                    departure_stop: 每一段的出发站
                    name: 线路名
                    polyline: 线路坐标的字符串
                    via_stops: 经过的站点
                */
                const { arrival_stop,departure_stop,name,polyline:{polyline},via_stops } = busline
                const line = {partStation:[],name:''}
                path.push({
                    name,
                    polyline,
                })
                // 如果是最后一段线路，则终点站为终点站，否则为换乘站
                index === segments.length - 1 || segments[index+1].bus.buslines===null? arrival_stop.type = '终点站' : arrival_stop.type = '换乘站'
                // 如果是第一段线路，则起点站为起点站，否则为换乘站
                index === 0 ? departure_stop.type = '起点站' : departure_stop.type = '换乘站'
                line.partStation.push(departure_stop)
                via_stops.forEach(stop=>{
                    stop.type = '途径站'
                    line.partStation.push(stop)
                })
                line.partStation.push(arrival_stop)
                line.name = name

                stations.push(line)
            })
        }
        flyToDefaultView(viewer)
    })
    // console.log(path,stations)


    // 渲染站点
    stations.forEach((item,index)=>{
        const { partStation } = item
        partStation.forEach(station=>{
            // console.log(station)
            const { name, location,type } = station
            const positionArr = location.split(',').map(pos=>Number(pos))
            const position = {lng:positionArr[0],lat:positionArr[1]}
            // 渲染站点
            const stationEnt = renderStation(viewer,{
                positions:position,
                name,
                color:type === '换乘站' ? '#e9a526':lineColors[index],
            })

            renderStationBill(viewer,{
                position:position,
                name,
                color:type === '换乘站' ? '#e9a526':lineColors[index],
                attr:{
                    name
                },
            },true)
            cacheData.stationEnts.push(stationEnt)
        })
    })

    // 渲染路线
    path.forEach((item,index)=>{
        console.log(item)
        const { name, polyline } = item
        const color = new Cesium.Color.fromCssColorString(lineColors[index])
        const polylineArr = polyline.split(';')
        const positions = polylineArr.map(pos=>{
            const posArr = pos.split(',').map(pos=>Number(pos))
            return posArr
        }).flat()
        // console.log(positions)
        const lineEnt  = renderLines(viewer,{
            positions,
            name,
            color,
        })
        cacheData.lineEnts.push(lineEnt)
    })
}
// 进入规划模式
const enterDesign = async ()=>{
    // 检查起点站和终点站是否存在
    if(startStation.value.length && endStation.value.length){
        const data = await getLineData()
        renderLine(data)
    }else{
        message.warn('请选择起点站和终点站')
        return
    }

    // 进入/退出规划模式
    isDesign.value = !isDesign.value
    !isDesign.value && leaveRouteDesign()

}

// 监听起点/终点站变化
watch([startStation,endStation],async ()=>{
    if(isDesign.value){
        const data = await getLineData()
        renderLine(data)
    }
})

// 删除实体
const removeActiveEnts = ()=>{
    removeByCacheData(viewer,cacheData,true)
    cacheData.stationEnts = []
    cacheData.billboards = []
    cacheData.lineEnts = []
    routeInfo.value.distance = []
    routeInfo.value.stations = []
}
// 离开规划模式
const leaveRouteDesign = ()=>{
    removeActiveEnts()
    lineData.controlAll(true)
    isDesign.value = false
    startStation.value = []
    endStation.value = []
}

let options = ref([])
onMounted(() => {
    viewer = lineData.Viewer
    subLineData.value = lineData.allData
    console.log(subLineData.value)
    if(subLineData.value.length > 0){
        options.value = subLineData.value.map(item=>{
            const { name, stationsList } = item
            const children = stationsList.map(s=>{
                return {
                    value: s.name,
                    label: s.name,
                }
            })
            return {
                label:name,
                value:name,
                children,
            }
        })
    }
    console.log(options.value)
})

onBeforeUnmount(()=>{
    leaveRouteDesign()
})


</script>
<style scoped>
/* 路径规划样式 */
.route-design-wrapper {
  position: absolute;
  right: 14%;
  top: 5%;
}

.route-design {
  width: 320px;
  height: 170px;
  background-color: rgba(0, 0, 0, 0.6);
  border: 1px solid #885f12;
}

.route-design > .header {
  width: 100%;
  height: 40px;
  color: #fff;
  padding-left: 10px;
  background: rgb(255, 255, 255);
  background-image: linear-gradient(
    180deg,
    rgba(255, 255, 255, 1) 9%,
    rgba(211, 156, 50, 1) 57%
  );
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  display: flex;
  align-items: center;
}

.route-design span {
  margin-left: 5px;
}

.content {
  width: 100%;
  height: 110px;
  pointer-events: all;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
  color: #fff;
}

.start-btn {
  width: 80px;
  color: #fff;
  margin-left: 140px;
  background-color: transparent;
  border: 1px solid #885f12;
  font-size: 12px;
  padding: 3px;
  pointer-events: all;
  cursor: pointer;
}

.start-btn:hover {
  background-color: #5c3f096d;
  border: 1px solid #881212;
}
</style>
